package com.ponxu.mb.model;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页信息
 * 
 * @author xwz
 */
public class PageInfo {
	private int pageSize = 20;
	private int pageIndex;
	private int totalPage;
	private int totalRow;
	private int from;
	private int to;

	public PageInfo(HttpServletRequest request) {
		try {
			String page = request.getParameter("page");
			this.pageIndex = Integer.parseInt(page);
		} catch (NumberFormatException e) {
		}
		if (pageIndex == 0) {
			pageIndex = 1;
		}
	}

	public PageInfo(int pageIndex) {
		this.pageIndex = pageIndex;
		if (pageIndex == 0) {
			pageIndex = 1;
		}
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public int getPageSize() {
		return this.pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public int getTotalRow() {
		return totalRow;
	}

	public void setTotalRow(int totalRow) {
		this.totalRow = totalRow;
		this.totalPage = (totalRow / pageSize)
				+ (totalRow % pageSize > 0 ? 1 : 0);

		// Google 分页
		from = pageIndex - 5;
		to = pageIndex + 4;
		int offset = 0;
		if (from < 1) {
			offset = Math.abs(from) + 1;
			from = 1;
		}
		if (offset > 0 && to < totalPage) {
			to += offset;
			if (to > totalPage) {
				to = totalPage;
			}
		}

		offset = 0;
		if (to > totalPage) {
			offset = to - totalPage;
			to = totalPage;
		}

		if (offset > 0 && from > 1) {
			from -= offset;
			if (from < 1) {
				from = 1;
			}
		}
	}

	public String mysqlLimit() {
		int offset = (pageIndex - 1) * pageSize;
		return " LIMIT " + offset + ", " + pageSize;
	}

	public int getFrom() {
		return from;
	}

	public int getTo() {
		return to;
	}

}
